<script lang="ts" setup>
import auth from '@/api/auth'
import mcht from '@/api/mcht'
import { useAuthStore, useHomeStore } from '@/store'
import { cleanStringCompact } from '@/utils/shared.ts'

const messageTemplateId = import.meta.env.VITE_MESSAGE_TEMPLATE_ID

const { openid, sessionid, token, backAfterLogin } = storeToRefs(useAuthStore())
const {
  mchtNo,
  shopId,
  phoneNumber,
  digitalCurrency,
  discount,
  transactionSummary,
  userName,
  roleFlag,
  msgSwitch,
  menuBit,
  bit8,
  bit10,
  adjustFlag,
  sb,
} = storeToRefs(useHomeStore())

const query = ref({})
onLoad((options: any) => {
  console.log('options')
  console.log(options)
  query.value = options
})

async function loginSuccess(data: any) {
  token.value = data.token
  sessionid.value = data.sessionid
  openid.value = data.openid
  mchtNo.value = data.mchtNo
  shopId.value = data.shopId || ''
  userName.value = data.userName
  roleFlag.value = data.roleFlag
  phoneNumber.value = data.userTel
  digitalCurrency.value = data.digitalCurrency
  discount.value = data.discount
  transactionSummary.value = data.transactionSummary
  msgSwitch.value = data.msgSwitch || '0'
  menuBit.value = data.menuBit || '000000000000'
  bit8.value = data.bit8 || '00000'
  bit10.value = data.bit10 || '00'
  adjustFlag.value = data.adjustFlag
  sb.value = data.sb
  checkSetting()
  // 判断密码是否快过期
  if (data.PSt) {
    console.log('data.PSt')
    console.log(data.PSt)
    console.log(data.PSt === 'valid')
    if (data.PSt === 'expired') {
      uni.showModal({
        title: '密码过期提醒',
        content: `您的登录密码已过期，是否立即修改？`,
        confirmText: '去修改',
        success: async (res) => {
          if (res.confirm) {
            uni.redirectTo({
              url: '/pages/login/force'
            })
          }
        }
      })
    }
    if (data.PSt === 'expiring_soon') {
      uni.showModal({
        title: '密码过期提醒',
        content: `您的登录密码即将在${data.daysLeft}天后过期，是否立即修改？`,
        cancelText: '忽略',
        confirmText: '去修改',
        success: async (res) => {
          if (res.confirm) {
            uni.redirectTo({
              url: '/pages/login/force'
            })
          } else if (res.cancel) {
            // 判断有无登录后需要跳转的页面
            if (backAfterLogin.value) {
              uni.reLaunch({
                url: backAfterLogin.value,
              })
            }
            else {
              uni.switchTab({
                url: '/pages/home/index',
              })
            }
          }
        }
      })
    }
    if (data.PSt === 'valid') {
      // 判断有无登录后需要跳转的页面
      if (backAfterLogin.value) {
        uni.reLaunch({
          url: backAfterLogin.value,
        })
      }
      else {
        uni.switchTab({
          url: '/pages/home/index',
        })
      }
    }
  }
}

function checkSetting() {
  wx.getSetting({
    withSubscriptions: true,
    success: async (res: any) => {
      // 查看设置，检查用户是否订阅了模板消息
      const subscribeStatus = res.subscriptionsSetting[messageTemplateId]
      console.log('subscribeStatus')
      console.log(subscribeStatus)
      if (subscribeStatus) {
        if (!(subscribeStatus).startsWith('accept')) {
          msgSwitch.value = '0'
          await mcht.setPushSwitch({
            msgSwitch: '0',
          })
        }
      }
    },
  })
}

onMounted(() => {
  // isLoginLoding.value = false
  // return
  uni.showLoading({
    title: '加载中',
  })
  wx.login({
    success: async (res) => {
      if (res.code) {
        // 先调用静默登录
        const { data } = await auth.loginAndQuery(res.code)
        if (data.status === 'success') {
          openid.value = data.data.openid
          isLoginLoding.value = false
          // 不保存token
          // token.value = data.data.token
          if (data?.data.needReset) {
            token.value = data.data.token
            reset()
          }
          else {
            if (data.data.loginStatus) {
              if (data.data.loginStatus === '1') {
                // 静默登录成功
                uni.hideLoading()
                loginSuccess(data.data)
              }
              // else if (data.data.loginStatus === '4') {
              //   uni.hideLoading()
              //   uni.redirectTo({
              //     url: `/pages/login/first`
              //   })
              // }
              else {
                uni.hideLoading()
              }
            }
            else {
              uni.hideLoading()
            }
          }
        }
        else if (data.status === 'expire' || data.status === 'tokenExpire') {
          openid.value = data.data.openid
          isLoginLoding.value = false
          uni.hideLoading()
        }
        else {
          isLoginLoding.value = false
          uni.hideLoading()
        }
      }
      else {
        uni.hideLoading()
      }
    },
  })
})

const form = ref({
  phone: '',
  id: '',
  type: '',
  code: '',
  password: '',
})

const merchantSelectRef = ref()

watch(() => form.value.phone, async (value) => {
  if (value.length >= 11) {
    merchantSelectRef.value.getList(value)
  }
})

const second = ref(0)
const interval = ref()
async function getCode() {
  if (form.value.phone === '') {
    uni.showToast({
      icon: 'none',
      title: '请先输入手机号',
    })
  }
  else if (form.value.id === '') {
    uni.showToast({
      icon: 'none',
      title: '请选择商户/门店',
    })
  }
  else {
    const { data } = await auth.getDynamicCode({
      phoneNumber: form.value.phone,
      merchantId: form.value.id,
    })
    if (data.status === 'success') {
      second.value = 60
      interval.value = setInterval(() => {
        second.value = second.value - 1
        if (second.value <= 0) {
          second.value = 0
          clearInterval(interval.value)
        }
      }, 1000)
    }
  }
}

const isLoginLoding = ref<boolean>(true)

const confirm = ref<boolean>(false)
const loading = ref<boolean>(false)
async function login() {
  if (form.value.phone === '') {
    uni.showToast({
      icon: 'none',
      title: '请先输入手机号',
    })
  }
  else if (form.value.id === '') {
    uni.showToast({
      icon: 'none',
      title: '请选择商户/门店',
    })
  }
  else if (form.value.code === '') {
    uni.showToast({
      icon: 'none',
      title: '请输入验证码',
    })
  }
  else if (form.value.password === '') {
    uni.showToast({
      icon: 'none',
      title: '请输入密码',
    })
  }
  else if (confirm.value) {
    loading.value = true
    let postData = {
      phoneNumber: form.value.phone,
      password: form.value.password,
      verificationCode: form.value.code,
    }
    if (form.value.type === 'M') {
      postData = Object.assign(postData, {
        mchtNo: form.value.id,
      })
    }
    if (form.value.type === 'S') {
      postData = Object.assign(postData, {
        storeId: form.value.id,
      })
    }
    const { data } = await mcht.loginAndQuery(postData)
    loading.value = false
    if (data.status === 'success') {
      if (data?.data.needReset) {
        sessionid.value = data?.data.sessionid
        token.value = data?.data.token
        reset()
      }
      else {
        loginSuccess(data.data)
      }
    }
    else {
      // 重置验证码和密码
      form.value.code = ''
      form.value.password = ''
    }
  }
  else {
    uni.showToast({
      icon: 'none',
      title: '请先接受协议',
    })
  }
}
function goRule() {
  uni.navigateTo({
    url: '/pages-sub/apply/agreement',
  })
}
function reset() {
  // 将页面两个字段置为空，以便从重置密码页面回来时，这两个字段是空的
  form.value.code = ''
  form.value.password = ''
  uni.navigateTo({
    url: `/pages/login/reset?phone=${form.value.phone}`,
  })
}
function forget() {
  uni.navigateTo({
    url: `/pages/login/forget-first?phone=${form.value.phone}`,
  })
}
// function first () {
//   uni.navigateTo({
//     url: '/pages/login/first',
//   })
// }

const passwordType = ref('password')
function handlePassword() {
  passwordType.value === 'password'
    ? (passwordType.value = 'text')
    : (passwordType.value = 'password')
}

// 处理输入事件
function handleInputPassword(inputName, event) {
  const value = event
  const filteredValue = cleanStringCompact(value)
  form.value[inputName] = filteredValue
}
</script>

<template>
  <div class="li-login">
    <!-- <div class="li-login-logo">
      <div class="i-ri:login-box-fill li-login-logo-img"></div>
    </div> -->
    <div class="li-login-title">商户登录</div>
    <div class="li-login-sub">请使用商户联系人手机号登录</div>
    <div style="margin-bottom: 200rpx;">
      <nut-form :model-value="form">
        <nut-form-item>
          <nut-input v-model="form.phone" placeholder="请输入手机号" input-class="li-login-ipt"
            placeholder-class="li-login-iptpl" />
        </nut-form-item>
        <nut-form-item>
          <login-merchant-select ref="merchantSelectRef" v-model="form.id" v-model:type="form.type" />
        </nut-form-item>
        <nut-form-item>
          <!-- <nut-input v-model="form.password" placeholder="请输入登录密码" :type="passwordType" input-class="li-login-ipt"
            placeholder-class="li-login-iptpl">
            <template v-if="passwordType === 'password'" #right>
              <div class="show-password" @click="handlePassword">
                <div class="i-ri:eye-fill"></div>
              </div>
            </template>
            <template v-else #right>
              <div class="show-password" @click="handlePassword">
                <div class="i-ri:eye-off-fill"></div>
              </div>
            </template>
          </nut-input> -->

          <nut-input v-if="passwordType === 'password'" v-model="form.password" placeholder="请输入登录密码"
            :type="passwordType" input-class="li-login-ipt" placeholder-class="li-login-iptpl"
            @input="handleInputPassword('password', $event)">
            <template #right>
              <div class="show-password" @click="handlePassword">
                <div class="i-ri:eye-off-fill"></div>
              </div>
            </template>
          </nut-input>

          <nut-input v-else v-model="form.password" placeholder="请输入登录密码" :type="passwordType"
            input-class="li-login-ipt" placeholder-class="li-login-iptpl"
            @input="handleInputPassword('password', $event)">
            <template #right>
              <div class="show-password" @click="handlePassword">
                <div class="i-ri:eye-fill"></div>
              </div>
            </template>
          </nut-input>
        </nut-form-item>

        <nut-form-item>
          <nut-input v-model="form.code" type="number" placeholder="请输入验证码" input-class="li-login-ipt"
            placeholder-class="li-login-iptpl">
            <template #right>
              <div class="li-login-ipt-btn" v-if="second === 0" @click="getCode">获取验证码</div>
              <div v-else class="li-login-ipt-btndis">{{ second }}</div>
            </template>
          </nut-input>
        </nut-form-item>

      </nut-form>
      <div class="rules">
        <div class="left">
          <nut-checkbox v-model="confirm" />
        </div>
        <div class="right">
          我已仔细阅读并接受
          <span class="rule" @click="goRule">《绵阳市商业银行股份有限公司隐私政策》</span>
        </div>
      </div>
      <nut-button type="primary" custom-class="login-btn shake_o" :loading="loading" block
        @click="login">登录</nut-button>
      <!-- 已有账号? -->
      <div class="login-forget">
        <span class="login-forget-text" @click="forget">忘记密码</span>
      </div>
    </div>
  </div>

  <div class="pos-loading" v-if="isLoginLoding">
    <div class="li-loader"></div>
    <div style="margin-top: 20rpx;">加载中</div>
  </div>
</template>

<route lang="json">{
  "style": {
    "navigationBarTitleText": "商户登录",
    "backgroundColorContent": "#ffffff"
  }
}</route>

<style lang="sass" scoped>
.login
  .top
    background-color: #fff
    text-align: center
    padding: 30px
    .title
      font-weight: bold
      font-size: 20px
      margin-bottom: 10px
    .desc
      color: #8e8e8e
      margin-bottom: 40px
    .form
      margin-top: 40px
      .space
        display: flex
        justify-content: space-around
        padding: 10px
    .rules
      padding: 0 20px
      display: flex
      .left
        width: 30px
      .rule
        color: #2196F3
  .button
    margin: 40px 20px

.rules
  padding: 0 20px
  display: flex
  .left
    width: 30px
  .rule
    color: #2196F3

.li-login
  width: 600rpx
  margin-left: 75rpx
  display: flex
  flex-direction: column
  align-items: center
  justify-content: center
  height: 100vh

:deep(.nut-cell-group__wrap)
  border-radius: 0!important
  box-shadow: none

:deep(.nut-cell-group__wrap .nut-cell)
  height: 100rpx
  background-color: #f8f8f8
  margin-bottom: 30rpx
  border-radius: 50rpx

:deep(.nut-form-item__body)
  justify-content: center

:deep(.li-login-ipt)
  color: #333

:deep(.li-login-iptpl)
  color: #d6d6d6

.li-login-ipt-btn
  color: #2196F3

.li-login-ipt-btndis
  color: #BBDEFB

.li-login-logo
  height: 80rpx
  width: 80rpx
  background: #E3F2FD
  border-radius: 12rpx
  display: flex
  align-items: center
  justify-content: center
  margin-top: 50rpx
  .li-login-logo-img
    color: #42A5F5
    font-size: 50rpx

.li-login-title
  font-size: 50rpx
  margin-top: 20rpx
  margin-left: 15rpx

.li-login-sub
  font-size: 28rpx
  color: #666666
  margin-top: 20rpx
  margin-bottom: 40rpx
  margin-left: 15rpx

:deep(.login-btn)
  width: 100%
  height: 85rpx
  margin-top: 30rpx
  background-color: #2196F3!important

.login-forget
  width: 100%
  margin-top: 30rpx
  display: flex
  align-items: center
  justify-content: center
  .login-forget-text
    color: #42A5F5
    margin-left: 5rpx

.pos-loading
  position: fixed
  top: 0
  left: 0
  right: 0
  bottom: 0
  background-color: #fff
  display: flex
  align-items: center
  justify-content: center
  flex-direction: column
  z-index: 99

:deep(.ovhide)
  overflow: hidden
  white-space: nowrap
  text-overflow: ellipsis
</style>
